# -*- coding:utf-8 -*-

import os
import shutil
import time
import traceback

from PIL import Image, ImageDraw, ImageFont
from git import Repo


class ImageWaterMarker:
    def __init__(self):
        pass

    @staticmethod
    def get_image_file_list(scan_path, exclude=""):
        result = []
        for parent, _, file_names in os.walk(scan_path):
            if exclude and parent.startswith(exclude):
                continue
            for file_name in file_names:
                file_ext = os.path.splitext(file_name)[-1].lower()
                if file_ext in [".jpg", ".jpeg", ".png", ".bmp"]:
                    result.append(os.path.join(parent, file_name))
        return result

    @staticmethod
    def handle_images(image_path, backup_path):
        # 获取图片列表
        image_list = ImageWaterMarker.get_image_file_list(image_path, backup_path)

        # 获取备份列表
        backup_list = ImageWaterMarker.get_image_file_list(backup_path)

        # 给未备份的图片加水印
        marked_image_list = []
        for file_full_name in image_list:
            file_related_name = file_full_name[len(image_path) + 1:]
            backup_full_name = ImageWaterMarker.gen_back_path(backup_path,
                                                              file_related_name)
            if backup_full_name not in backup_list:
                print("mark image: {}".format(file_full_name))
                # 备份原始图片
                ImageWaterMarker.safe_mkdir(os.path.split(backup_full_name)[0])
                shutil.copyfile(file_full_name, backup_full_name)
                try:
                    # 加水印
                    ImageWaterMarker.add_mark(file_full_name)
                except Exception as e:
                    print("{}".format(e))
                    print(traceback.format_exc())
                    shutil.copyfile(backup_full_name, file_full_name)
                    os.remove(backup_full_name)

                marked_image_list.append(file_related_name)

        print("marked list: {}".format(marked_image_list))
        return marked_image_list

    @staticmethod
    def gen_back_path(backup_path, relative_path):
        #split_path = os.path.splitext(relative_path)
        backup_full_name = os.path.join(backup_path, relative_path)
        return backup_full_name

    @staticmethod
    def safe_mkdir(target_dir):
        if not os.path.exists(target_dir):
            os.makedirs(target_dir)

    @staticmethod
    def add_mark(image_file_name):
        img = Image.open(image_file_name)
        max_width = 1280
        max_height = 960
        if img.size[0] > img.size[1]:
            if img.size[0] > max_width:
                img = img.resize((max_width, int(float(max_width) / (img.size[0]) * img.size[1])))
        else:
            if img.size[1] > max_height:
                img = img.resize((int(float(max_height) / (img.size[1]) * img.size[0]), max_height))

        draw = ImageDraw.Draw(img)

        fillcolor = "#ff0000"
        myfont = ImageFont.truetype('Arial Unicode', size=25)
        width, height = img.size
        draw.text((width - 250, height - 35), '码小侠 codingxx.com', font=myfont, fill=fillcolor)
        if img.mode != "RGB":
            img = img.convert('RGB')
        img.save(image_file_name, "JPEG", quality=85)


if __name__ == "__main__":
    repo_pic = '/Users/ferrisyu/source/codingxx_pictures/marked_res'
    # repo = Repo(repo_pic)
    # git = repo.git
    # print(git.reset('--hard'))
    # print(git.clean('-xdf'))
    # print(git.pull())

    marker = ImageWaterMarker()
    marked_list = marker.handle_images(repo_pic,
                                       repo_pic + r"/backup")

    #with open('/tmp/marked_list.txt', 'w') as f:
    #    for file_name in marked_list:
    #        f.write('https://purge.jsdelivr.net/gh/yu-fei/pictures@master/marked/' + file_name + "\n")

    # if repo.is_dirty() or len(repo.untracked_files) > 0:
    #     print(git.add('--all', '.'))
    #     print(git.commit('-m', "add mark to image " + time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
